<?php
require_once("page.class.php");
require_once("db_functions.php");
require_once("functions.php");

define(PAGE_SIZE,10);
	
class duznici extends page {
	var $db;
	
	var $ugo;
	
	function duznici(){
		$this->loadConfig();
		$this->db = new db_functions();
		$action = getFromInput("a");
		switch ($action){
			case "searchUgo":
				/*$uri = $_SERVER['REQUEST_URI'];
				$params = substr($uri,strpos($uri,"?"));
				$remotepath = "http://cvet.yellow/yap1/duznici.php";
				$include = $remotepath.$params;
				$html = file($include);
				//print_rarray($html);
				//echo $include."<br />".$uri;
				echo implode("",$html);*/
				$this->searchUgo();
				break;
			case "callhistory":
				$this->callHistory();
				break;
			case "alarm":
				$this->updateAlarms();
				break;
			case "add":
				$this->addCall();
				break;
			case "report":
				$this->reportDuznici();
				break;
			case "monthreport":
				$this->reportDuzniciByMonth();
				break;
			case "calls":
				$mod = getFromInput("mod");
				switch ($mod){
					case "searchOdgovor":
						$this->SearchOdgovor();
						break;
					default:
						$this->callsAdmin();
				}
				break;
			case "pozivaoci":
				$this->reportPozivaoci();
				break;
			case "za_pozivanje":
				$this->zaPozivanje();
				break;
			default:
				$this->_main();
				break;
		}
	}
	
	function _main(){
		$polja = $this->get_Odgovori();
			$this->assign("odgovor_id",$polja["polje_id"]);
			$this->assign("odgovor_name",$polja["polje_name"]);
		$polja = $this->get_Ishodi();
			$this->assign("ishod_id",$polja["polje_id"]);
			$this->assign("ishod_name",$polja["polje_name"]);
		$zaPozivanje=$this->zaPozivanje();
		$this->assign("za_pozivanje",$zaPozivanje);
		echo $this->parseTemplate("duznici/duznici.tpl");
	}
	
	function searchUgo(){
		$k = readValFromInput("kword");
		$objid = getFromInput("objid");
		$objbroj = getFromInput("objbroj");
		$objkomid = getFromInput("komid");
		$objkomname = getFromInput("komname");
		
		$this->assign("search_kword",$k);
		
		$q = "SELECT id, broj, datum, komitent, komitent_name, iznos_bruto, tip_ugovora "
			."FROM ugovori, komitenti "
			."WHERE komitenti.komitent_id=ugovori.komitent AND ("
			."ugovori.id='$k' "
			."OR broj LIKE '%$k%' "
			."OR komitent='$k' "
			."OR komitent_name LIKE '%$k%' "
			."OR komitent_ziro LIKE '%$k%') "
			."LIMIT 0,50";
		$res = $this->db->select2($q);
		$this->assign("search_length",$res!==false?count($res):"0");
		
		if ($res !== false) {
			foreach ($res as $k=>$row){
				$id = $row["id"];
				$broj = $row["broj"];
				
				$num[]	= $broj;
				
				// dugovanje
				$q = "SELECT SUM(iznos) FROM ugovori_otplate WHERE ugoid=$id";
				$otplata = floatval($this->db->getOne($q));
				$dug = $row["iznos_bruto"]-$otplata;
				$dug = $dug>0?' <span style="margin-right:5px; float:right; color:red"><strong>'.number_format($dug,2,",",".").'</strong></span>':"";
				
				// storno
				//$stornoHTML = '<img style="margin:2px 5px;" src="gui/icons/storno.gif" align="right" border="0" alt="storno" />';
				$stornoHTML = "<span style=\"float:right; margin:0px 5px; color:#f00; font-weight:bolder;\">storno</span>";
				$storno = intval($row["tip_ugovora"])==5?" $stornoHTML":"";
				
				$komid = $row["komitent"];
				$komname = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$row["komitent"]." LIMIT 1");
				$komitent = "$komid. $komname";
				$info = datetime2str($row["datum"]);
				$price = "<span style=\"float:right\"><strong>".number_format($row["iznos_bruto"],2,",",".")."</strong></span>";
				$item[] = $price.$dug.$storno."<h1>$komitent</h1><span class=\"info\">$info</span>";
				
				$q = "SELECT komitent_vlasnik_name, komitent_direktor, komitent_direktor_tel, komitent_predst, komitent_predst_tel "
					."FROM komitenti "
					."WHERE komitent_id=".$row["komitent"]
					." LIMIT 1";
				$contacts = $this->db->getRow($q);
				if ($contacts) {
					$telefon = $this->db->getOne("SELECT telefon FROM komitenti_telefoni WHERE fax=0 AND kom_id=".$row["komitent"]." AND del_id=0 ORDER BY `order` LIMIT 1");
					$_contacts = array();
					if (strlen($contacts[0])>0) {
						$_contacts[] = $contacts[0]." (vlasnik){!!}".$telefon;
					}
					if (strlen($contacts[1])>0) {
						$_contacts[] = $contacts[1]." (direktor){!!}".$contacts[2];
					}
					if (strlen($contacts[3])>0) {
						$_contacts[] = $contacts[3]." (predstavnik){!!}".$contacts[4];
					}
					
					if (count($_contacts)>0) {
						$_c = implode("{!}",$_contacts);
					}
				}
				
				$func = "closeYpAjaxForm(); updateSelectUgovor('$objbroj','$objid','".$objkomid."','".$objkomname."','".$row["broj"]."','".$row["id"]."','".$row["komitent"]."','".addslashes($row["komitent_name"])."'); updateDuzniciContacts('$_c'); duzniciUpdateKomitentDetails(); duzniciCallhistory();";
				$onclick[] = $func;
			}
			$this->assign("list_num",$num);
			$this->assign("list_item",$item);
			$this->assign("onclick",$onclick);
		}
		
		echo $this->parseTemplate("search_list.tpl");
	}
	
	function searchUgo1(){
		$kword = readValFromInput("kword");
		$objid = getFromInput("objid");
		$komid = getFromInput("komid");
		$komname = getFromInput("komname");
		
		$this->assign("search_kword",$kword);
		
		$query_fields = array(
			"u.komitent_ziro"=>"string",
			"k.komitent_name"=>"string",
			"k.komitent_name1"=>"string",
			"u.id"=>"integer",
			"u.broj"=>"string",
			"u.saradnik"=>"integer",
			"CONCAT(r.radnik_ime,' ',r.radnik_prezime)"=>"string"
		);
		
		$q = "SELECT "
				."u.id, u.broj, u.iznos_bruto, u.datum, u.komitent_ziro, u.tip_ugovora, u.napomena, "
				."k.komitent_id, k.komitent_name, k.komitent_predst, "
				."r.radnik_ime, r.radnik_prezime "
			."FROM ugovori u, komitenti k, radnici r "
			."WHERE k.komitent_id=u.komitent "
			."AND u.saradnik=r.radnik_id AND(0";
			
		foreach ($query_fields as $fld=>$type){
			if($type == "string"){
				$skw = prepForSQL($kword);
				$q .= " OR $fld LIKE '%$skw%'";
			}else{
				$skw = intval($kword);
				if($kword>0){
					$q .= " OR $fld=$skw";
				}
			}
		}
		$q .= ") ORDER BY k.komitent_name ASC, u.datum DESC, u.iznos_bruto DESC";
		
		$res = $this->db->select2($q);
		$ukupno = 0;
		if ($res !== false) {
			$ukupno = count($res);
			foreach ($res as $k=>$v){
				
				$nums[$k] = $v["broj"];
				$cena[$k] = number_format($v["iznos_bruto"],2,",",".");
				$parname[$k] = $v["komitent_name"];
				$parid[$k] = $v["komitent_id"];
				$datum[$k] = datetime2str($v["datum"]);
				$radnik[$k] = $v["radnik_ime"]." ".$v["radnik_prezime"];
				$ziro[$k] = $v["komitent_ziro"];
				$predstavnik[$k] = $v["komitent_predst"];
				
				$q = "SELECT kampanja_id, kampanja_naziv FROM ugovori_stavke, kampanje WHERE ugovori_stavke.kampanja=kampanje.kampanja_id AND ugovori_stavke.ugovor_id=".$v["id"]." LIMIT 1";
				list($kampanja_id[$k],$kampanja_name[$k]) = $this->db->getRow($q);
				
				$napomena[$k]	= strlen($v["napomena"])>0?'<img src="gui/icons/napomena.gif" onclick="event.stopPropagation();displayDuzniciNapomena(this)" />':"";
				$napomena_txt[$k] = $v["napomena"];
				
				
				// artikli
				$_artikli = $this->db->select2("SELECT stavka_id, artikl, paket, delatnost, kolicina, iznos_bruto FROM ugovori_stavke WHERE ugovor_id=".$v["id"]);
				$a = "";
				foreach ($_artikli as $m=>$art){
					
					if ($art["paket"]>0) {
						
					}else{
						$tmp = $this->get_CeneArtikl($art["artikl"]);
						$artname = $tmp["art_name"];
					}
					
					
					$delid = $art["delatnost"];
					$delname = $this->db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1");
					
					$info = "";
					$info .= '<img alt="d" src="gui/icons/delatnost.gif" title="'.$delid." - ".$delname.'" onclick="event.stopPropagation(); alert(\''.$delid.". ".$delname.'\')" />';
					
					// materijal
					$q = "SELECT 1 FROM ugovori_tok_realizacije utr, tok_materijali tm "
						."WHERE utr.stavka=".$art["stavka_id"]." "
						."AND utr.tok_id=tm.tok "
						."AND tm.upotrebljiv=1 "
						."LIMIT 1";
					$imamat = $this->db->getOne($q);
					if($imamat){
						$info .= '<img alt="m" src="gui/icons/materijal.gif" title="materijal je potpun" onclick="event.stopPropagation()" />';
						//$info .= '<a href="javascript:void(0)" title="materijal je potpun" onclick="event.stopPropagation()">m</a>';
					}
					
					// uradjen
					$q = "SELECT 1 FROM ugovori_tok_realizacije utr, ugovori_tok_actions uta "
						."WHERE utr.stavka=".$art["stavka_id"]." "
						."AND utr.tok_id=uta.tok "
						."AND uta.done=1 "
						."LIMIT 1";
					$uradjen = $this->db->getOne($q);
					if($uradjen){
						$info .= '<img alt="u" src="gui/icons/uradjeno.gif" title="uradjeno" onclick="event.stopPropagation()" />';
						//$info .= '<a href="javascript:void(0)" title="uradjeno" onclick="event.stopPropagation()">u</a>';
					}
					
					/*if(strlen(trim($_profil[$m])) || strlen(trim($_profile[$m]))){
						if(strlen(trim($_profil[$m]))){
							$pp = "srpski:\\n".addslashes(trim($_profil[$m]))."\\n\\n";
						}
						if(strlen(trim($_profile[$m]))){
							$pp.= "engleski:\\n".addslashes(trim($_profile[$m]));
						}
						$info .= '<img alt="u" src="gui/icons/profil.gif" title="ima profil" onclick="event.stopPropagation(); alert(\''.$pp.'\')" />';
					}*/
					
					$a .= '<span class="artitem"><span class="artname">'.$art["kolicina"].' x ';
					if(strlen($artname)>30){
						$a .= substr($artname,0,30)."...";
					}else{
						$a .= $artname;
					}
					$a .= '</span><span class="artinfo">'.$info.'</span><span class="artprice">'.number_format($art["iznos_bruto"],2,",",".").'</span></span>';
				}
				$artikli[$k] 		= $a;
				
				
				// plan otplate
				$plan = $this->db->getRow("SELECT * FROM ugovori_plan_otplate WHERE ugovor_id=".$v["id"]." LIMIT 1",true);
				$pocode = "";
				if($plan["avans_bruto"]>0){
					$pocode .= '<span class="po_date">'.datetime2str($plan["avans_date"]).'</span><span class="po_val"><strong>A</strong> '.number_format($plan["avans_bruto"],2,",",".").'</span>';
				}
				if ($plan["broj_rata"]>0) {
					$rate = $this->db->select2("SELECT * FROM ugovori_plan_rate WHERE rata_plan=".$plan["plan_id"]." ORDER BY datum");
					foreach ($rate as $m=>$r){
						$pocode .= '<span class="po_date">'.int2date($r["datum"]).'</span><span class="po_val">'.number_format($r["bruto"],2,",",".").'</span>';
					}
					$pocodes[$k]		= $pocode;
				}
				
				// otplate
				$otplaceno = 0;
				$otplata = $this->db->select2("SELECT * FROM ugovori_otplate WHERE ugoid=".$v["id"]." ORDER BY datum");
				if ($otplata!==false) {
					$ocode = "";
					foreach ($otplata as $m=>$o){
						$otplaceno += $o["iznos"];
						$ocode .= '<span class="po_date">'.int2date($o["datum"]).'</span><span class="po_val">'.number_format($o["iznos"],2,",",".").'</span>';
					}
					$ocodes[$k]		= $ocode;
				}
				$dddug = $v["iznos_bruto"]-$otplaceno;
				$dug[$k] = $dddug>0?'<span style="color:red">'.number_format($dddug,2,",",",").'</span>':"";
				
				$q = "SELECT komitent_vlasnik_name, komitent_direktor, komitent_direktor_tel, komitent_predst, komitent_predst_tel "
					."FROM komitenti "
					."WHERE komitent_id=".$v["komitent_id"]
					." LIMIT 1";
				$contacts = $this->db->getRow($q);
				if ($contacts) {
					$telefon = $this->db->getOne("SELECT telefon FROM komitenti_telefoni WHERE fax=0 AND kom_id=".$v["komitent_id"]." AND del_id=0 ORDER BY `order` LIMIT 1");
					$_contacts = array();
					if (strlen($contacts[0])>0) {
						$_contacts[] = $contacts[0]."{!!}".$telefon;
					}
					if (strlen($contacts[1])>0) {
						$_contacts[] = $contacts[1]."{!!}".$contacts[2];
					}
					if (strlen($contacts[3])>0) {
						$_contacts[] = $contacts[3]."{!!}".$contacts[4];
					}
					
					if (count($_contacts)>0) {
						$_c = implode("{!}",$_contacts);
					}
				}
				
				// after func
				$afterFunc[$k] = " updateSelectUgovor('$objid','".$komid."','".$komname."','".$v["broj"]."','".$v["komitent_id"]."','".addslashes($v["komitent_name"])."'); updateDuzniciContacts('$_c');";
			}
			
			$this->assign("list_num",$nums);
			$this->assign("ukupno",$cena);
			$this->assign("dug",$dug);
			$this->assign("partner",$parname);
			$this->assign("partner_id",$parid);
			$this->assign("datum",$datum);
			$this->assign("radnik",$radnik);
			$this->assign("ziro",$ziro);
			$this->assign("parpred",$predstavnik);
			$this->assign("kampanja_id",$kampanja_id);
			$this->assign("kampanja",$kampanja_name);
			$this->assign("napomena",$napomena);
			$this->assign("napomena_txt",$napomena_txt);
			$this->assign("artikli",$artikli);
			
			$this->assign("plan_otplate",$pocodes);
			$this->assign("otplata",$ocodes);
			
			$this->assign("afterFunc",$afterFunc);
		}
		$this->assign("search_length",sprintf("%s",$ukupno));
		echo $this->parseTemplate("ugovori/search_list_duznici.tpl");
	}
	
	function SearchOdgovor(){
		$kword = readValFromInput("kword");
		$found = 0;
		
		if (strlen($kword)) {
			$q = "SELECT * FROM duznici_odgovori WHERE odgovor_name LIKE '%$kword%'";
			$res = $this->db->select2($q);
			if ($res !== false) {
				$found = 1;
				foreach ($res as $k=>$row){
					$nums[$k] = $k;
					$label[$k] = $row["odgovor_name"];
					$action[$k] = "duzniciSetOdgovor('".$row["odgovor_id"]."','".prepForSQL($row["odgovor_name"])."')";
				}
				$this->assign("num",$nums);
				$this->assign("label",$label);
				$this->assign("action",$action);
				
				$list = $this->parseTemplate("quick_search_list.tpl");
			}
		}
		echo "$found{!}$list";
	}
	
	function callHistory(){
		
		$komid = getFromInput("id");
		$userid = $this->getUserId();
		
		$q = "SELECT d.*, do.odgovor_name, di.name, rad.radnik_ime as ime, rad.radnik_prezime as prezime "
			."FROM duznici d, duznici_odgovori do, duznici_ishodi di, radnici rad, users u "
			."WHERE d.komitent=$komid "
			."AND do.odgovor_id=d.odgovor "
			."AND d.user=u.id "
			."AND d.ishod=di.id "
			."AND u.radnik_id=rad.radnik_id "
			."ORDER BY time DESC";
		$res = $this->db->select2($q);
		//echo "1{!}<li value=\"21\">$q</li>"; die();
		
		if ($res !== false) {
			$num=0;
			foreach ($res as $k=>$row){
				/*if ($row["user"] == $userid) {
					$num++;
				}*/
				$num++;
				
				if (strlen($row["napomena"])) {
					$options = '<img src="gui/icons/napomena.gif" onclick="alert(\''.preg_replace('/\r*\n/',"\\n",addslashes($row["napomena"])).'\')" style="cursor:pointer" />';
				}else{
					$options = "";
				}
				
				$desc = "";
				
				if ($row["odgovor"] == 6) {
					$row["odgovor_name"] = str_replace("__",$row["uplatazadana"],$row["odgovor_name"]);
				}
				$desc .= "<strong>".$row["kontakt_name"]." [".$row["kontakt_tel"]."]: </strong><i>".$row["odgovor_name"]."</i>";
				
				if ($row["obecanauplata"]>0) {
					$desc .= "<br />OBEĆANO: ".$row["obecanauplata"];
				}
				
				$desc .= "<br />ZAKLJUČAK: ".$row["name"];
				if ($row["ishod_time"]>0) {
					$desc .= ", ".date($this->getFromConfig("long_date"),$row["ishod_time"]);
				}
				if (strlen($row["ishod_desc"])>0) {
					$desc .= ", ".$row["ishod_desc"];
				}
				
				
				$history_i[] = $k;
				$history_options[] = $options;
				$history_ord[] = count($res)-$k;
				$history_time[] = date($this->getFromConfig("long_date"),$row["time"]);
				$history_user[] = $row["ime"]." ".$row["prezime"];
				$history_desc[] = $desc;
			}
			$this->assign("h_i",$history_i);
			$this->assign("h_options",$history_options);
			$this->assign("h_ord",$history_ord);
			$this->assign("h_user",$history_user);
			$this->assign("h_time",$history_time);
			$this->assign("h_desc",$history_desc);
			
			echo "$num{!}";
			echo $this->parseTemplate("rokovnik/history_list.tpl");
		}else{
			echo "0{!}";
		}
	}
	function updateAlarms(){
		
		$day = 60*60*24;
		$start = makeUnixTime(0,0,0,date("m"),date("d"),date("Y"));
		$end = $start+$day;
		$user = $this->getUserId();
		
		$q = "SELECT d.*, di.name, do.odgovor_name "
			."FROM duznici d, duznici_odgovori do, duznici_ishodi di "
			."WHERE (d.ishod=3 AND ((d.ishod_time>=$start AND d.ishod_time<$end)"
			//." OR d.ishod_time=0)"
			.")) "
			."AND do.odgovor_id=d.odgovor "
			."AND di.id=d.ishod "
			."AND user=$user "
			."ORDER BY d.time DESC, d.ishod_time ASC";
		$res = $this->db->select2($q);
		if ($res === false) {
			die("0");
		}else{
			
			foreach ($res as $row){
				$ids[] = $row["id"];
				$ishodi[] = $row["name"];
				
				$qc = "SELECT 1 FROM duznici WHERE ishod_time>".$row["ishod_time"]." AND komitent=".$row["komitent"];
				$call = $this->db->getOne($qc);
				
				if (!$call) {
					$called[] = "";
				}else{
					$called[] = " called";
				}
				
				$komitent[] = $this->db->getOne("SELECT komitent_name FROM komitenti WHERE komitent_id=".$row["komitent"]);
				$call_times[] = date("H:i",$row["ishod_time"]);
				
				$radnik[] = $this->db->getOne("SELECT CONCAT(radnik_ime,' ',radnik_prezime) FROM radnici, users WHERE users.radnik_id=radnici.radnik_id AND users.id=".$row["user"]);
				$radnik_time[] = date($this->getFromConfig("long_date"),$row["time"]);
				
				
				$kont = $row["kontakt_name"];
				if (strlen($row["kontakt_tel"])) {
					$kont .= " (".ipPhoneLink($row["kontakt_tel"]).")";
				}
				$kontakt[] = $kont;
				
				if ($row["odgovor"]==6) {
					$row["odgovor_name"] = str_replace("__",$row["uplatazadana"],$row["odgovor_name"]);
				}
				$odgovor[] = $row["odgovor_name"];
				
				if ($row["obecanauplata"]>0) {
					$obuplata[] = "<span style=\"font-size: 11px; display:block; margin-top:5px;\">OBEĆANO: ".$row["obecanauplata"]."</span>";
				}else{
					$obuplata[] = "";
				}
			}
			
			$this->assign("alarm_id",$ids);
			$this->assign("ishod",$ishodi);
			$this->assign("komitent",$komitent);
			$this->assign("called",$called);
			$this->assign("call_time",$call_times);
			$this->assign("radnik",$radnik);
			$this->assign("radnik_time",$radnik_time);
			$this->assign("kontakt",$kontakt);
			$this->assign("odgovor",$odgovor);
			$this->assign("obuplata",$obuplata);
			
			echo count($res)."{!}";
			echo $this->parseTemplate("duznici/duznici_alarms.tpl");
		}
	}
	
	function callsAdmin(){
		
		echo $this->parseTemplate("duznici/admin_calls.tpl");
	}
	
	function addCall(){
		$ugovor = getFromInput("ugovor");
		$komitent_id = getFromInput("komitent_id");
		$date = time();
		
		//echo "Testiranje u toku...\n\n$komitent_id\n$ugovor";die();
		
		$kontakt = readValFromInput("kontakt");
		$kontakt_other = readValFromInput("kontakt_drugi");
		
		if ($kontakt==-1) {
			$kontakt = $kontakt_other;
			$kontakt_tel = getFromInput("kontakt_tel_drugi");
		}else{
			$tmp = explode("{!!}",$kontakt);
			$kontakt = $tmp[0];
			$kontakt_tel = $tmp[1];
		}
		
		$kontakt = $kontakt!="-1"?$kontakt:$kontakt_other;
		
		$obuplata = getFromInput("obuplata");
		$obuplata = str_replace(",",".",$obuplata);
		$lastpos = strripos($obuplata,".");
		if($lastpos>=0){
			$first  = preg_replace('/[^\d]/',"",substr($obuplata,0,$lastpos));
			$second = substr($obuplata,$lastpos+1);
			$obuplata = "$first.$second";
		}else{
			$obuplata = preg_replace('/[^\d]/',"",$obuplata);
		}
		
		
		//echo "$obuplata\n\n";
		
		
		$odgovor = getFromInput("odgovor");
		$odgovor_dana = getFromInput("odgovor_dana");
		if($odgovor!=6){
			$odgovor_dana=0;
		}
		
		$napomena = readValFromInput("napomena");
		$ypu = $_COOKIE["ypu"];
		if (!strlen($ugovor) || !strlen($komitent_id) || !($kontakt || $kontakt_other) || ($odgovor==6 && strlen($odgovor_dana)<1)) {
			die("niste popunili sva obavezna polja.");
		}
		
		$ishod = getFromInput("ishod");
		$result_date = getFromInput("result_date");
		if (strlen(trim($result_date))>0) {
			$result_date = explode(".",$result_date);
			$ishod_time = makeUnixTime(getFromInput("result_hour"),getFromInput("result_minute"),0,$result_date[1],$result_date[0],$result_date[2]);
		}else{
			$ishod_time=0;
		}
		$ishod_desc = readValFromInput("result_desc");
		
		$q = "INSERT INTO "
			."duznici(user,time,ugovor,komitent,kontakt_name,kontakt_tel,odgovor,uplatazadana,obecanauplata,napomena,ishod,ishod_time,ishod_desc) "
			."VALUES($ypu,$date,'$ugovor',$komitent_id,'$kontakt','$kontakt_tel',$odgovor,$odgovor_dana,'$obuplata','".addslashes($napomena)."',$ishod,$ishod_time,'".addslashes($ishod_desc)."')";
		//die($q);
		if($this->db->alterTable($q)){
			echo "Poziv je zabeležen.";
		}else{
			echo mysql_error();
		}
	}
	function reportDuznici(){
		
		$fdat = getFromInput("filter_datum");
		$fdatint= date2int($fdat);
		$fu = intval(getFromInput("filter_ugovor"));
		$fkom = readValFromInput("filter_komitent");
		$fkon = readValFromInput("filter_kontakt");
		$fo = getFromInput("filter_odgovor");
		$fi = getFromInput("filter_ishod");
		
		$fou = getFromInput("filter_obuplata");
		$fou = isset($fou)?($fou>=0)?($fou>0)?1:0:-1:-1;
		
		$fup= getFromInput("filter_uplata");
		$fr = getFromInput("filter_radnik");
		
		$this->assign("filter_datum",$fdat);
		$this->assign("filter_ugovor",$fu);
		$this->assign("filter_komitent",$fkom);
		$this->assign("filter_kontakt",$fkon);
		
		$fous	 = array("0","1");
		$fou_lbl = array("ne","da");
		
		if($fou>=0){
			if($fou>0){
				$fou_sel = array("", " selected");
			}else{
				$fou_sel = array(" selected","");
			}
		}
	
		$this->assign("fou",$fous);
		$this->assign("fou_label",$fou_lbl);
		$this->assign("fou_sel",$fou_sel);
		
		$polja = $this->get_Odgovori($fo);
			$this->assign("odgovor_id",$polja["polje_id"]);
			$this->assign("odgovor_name",$polja["polje_name"]);
			$this->assign("odgovor_selected",$polja["polje_selected"]);
		$this->assign("filter_uplata",$fup);
		
		$this->assign("uplata_display",($fo==6)?"display: block;":"");
		$polja = $this->get_Radnici($fr);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
			$this->assign("radnik_selected",$polja["polje_selected"]);
			
		
		$polja = $this->get_Ishodi($fi);
			$this->assign("ishod_id",$polja["polje_id"]);
			$this->assign("ishod_name",$polja["polje_name"]);
			$this->assign("ishod_selected",$polja["polje_selected"]);
				
		$setted = false;
		foreach ($_POST as $k=>$v){
			if(strlen($v)>0 && $v>=0 && !preg_match('/^a$/i',$k)){
				//echo "$k="; var_dump($v);
				$setted = true;
				break;
			}
		}
		
		if(count($_POST)>0 && $setted){
			$q = "SELECT d.*, do.odgovor_name, di.name as ishod_name,di.id as ishod_id, k.komitent_name, r.radnik_ime, r.radnik_prezime,ugo.id as ugovor_id "
				."FROM duznici d, duznici_odgovori do, duznici_ishodi di, komitenti k, radnici r, users u,ugovori ugo "
				."WHERE d.odgovor=do.odgovor_id "
				."AND d.ishod=di.id "
				."AND k.komitent_id=d.komitent "
				."AND r.radnik_id=u.radnik_id "
				."AND u.id=d.user "
				." AND ugo.broj=d.ugovor ";
			
			
			if($fdatint>0){
				$day = 60*60*24;
				$q .= "AND d.time>=$fdatint AND d.time<".($fdatint+$day)." ";
			}
			if($fu>0){
				$q .= "AND ugovor=$fu ";
			}
			if(strlen($fkom)>0){
				if(preg_match('/[^\d]/',$fkom)){
					$q .= "AND k.komitent_name LIKE '%$fkom%' ";
				}else{
					$q .= "AND d.komitent=$fkom ";
				}
			}
			if(strlen($fkon)>0){
				$q .= "AND kontakt_name LIKE '%$fkon%'";
			}
			if($fo>0){
				$q .= "AND odgovor=$fo ";
				if($fo ==6 && strlen($fup)>0){
					$q .= "AND uplatazadana=$fup ";
				}
			}
			if ($fr>=0) {
				$q .= "AND u.radnik_id=$fr ";
			}
			if($fou>=0){
				if($fou>0)
					$q .= "AND obecanauplata>0 ";
				else
					$q .= "AND obecanauplata=0 ";
			}
			if($fi>0){
				$q .= "AND ishod=$fi ";
			}
				
			$q .= "ORDER BY time DESC";
			
			$res = $this->db->select2($q);
			if($res !== false){
				$ob_sum = 0;
				foreach ($res as $row){
					$ids[]			= $row["id"];
					$ugovori[]		= $row["ugovor"];
					$komitenti[]	= $row["komitent_name"];
					$komitenti_ids[]= $row["komitent"];
					$datumi[]		= date($this->getFromConfig("short_date1"),$row["time"]);
					$kontakti[]		= $row["kontakt_name"]."<br />".$row["kontakt_tel"];
					$odgovori[]		= ($row["odgovor"]==6)?($row["uplatazadana"]==0)?"uplata danas":str_replace("__"," ".$row["uplatazadana"]." ",$row["odgovor_name"]):$row["odgovor_name"];
					$ob_uplate[]	= number_format($row["obecanauplata"],2,",",".");
					$ob_sum		   += (float) $row["obecanauplata"];
					$uplate[]		= $row["uplatazadana"];
					$users[]		= $row["user"];
					$radnici[]		= $row["radnik_ime"]." ".$row["radnik_prezime"];
					$napomene[]		= nl2br($row["napomena"]);
					if ($row["ishod_id"]==1){ //predracun
						$func = "LoadRSDoc(\'predracun.php?a=make&id=".$row["ugovor_id"]."\',\'setContent\');";
						$ishod = "<a href=\"javascript:void(0)\" onclick=\"blankTarget('$func');\">".$row["ishod_name"]."</a>";
					}
					else $ishod = "<strong>".$row["ishod_name"]."</strong>";
					
					if($row["ishod_time"]){
						$ishod .= "<br />".date($this->getFromConfig("long_date1"),$row["ishod_time"]);
					}
					
					if($row["ishod_desc"]){
						$ishod .= "<br /><div style=\"font-size:10px;\">";
						$ishod .= '<a href="javascript:void(0)" onclick="alert(this.nextSibling.value);">opis</a>';
						$ishod .= '<textarea style="display:none;">'.$row["ishod_desc"].'</textarea>';
						$ishod .= "</div>";
					}
					
					
					
					$ishodi[]	= $ishod;
				}
				$this->assign("info",count($res)." poziva<br />obećano: ".number_format($ob_sum,2,",",".")." din.");
				$this->assign("row",$ids);
				$this->assign("datum",$datumi);
				$this->assign("ugovor",$ugovori);
				$this->assign("komitent",$komitenti);
				$this->assign("komitent_id",$komitenti_ids);
				$this->assign("kontakt",$kontakti);
				$this->assign("odgovor",$odgovori);
				$this->assign("obecana_uplata",$ob_uplate);
				$this->assign("napomena",$napomene);
				$this->assign("radnik",$radnici);
				
				$this->assign("ishod",$ishodi);
				
			}else{
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->Nema poziva");
			}
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","--><< Odaberite željeni kriterijum pretrage");
		}
		
		echo $this->parseTemplate("duznici/report_duznici.tpl");
	}
	function reportDuzniciByMonth(){
		
		$date = getFromInput("date");
		if (strlen($date)) {
			$this->assign("date",$date);
			
			$uri = $_SERVER['REQUEST_URI'];
			$params = "?a=monthreport&date=$date";
			
			$remotepath = "http://cvet.yellow/yap1/duznici.php";
			$include = $remotepath.$params;
			$html = file($include);
			$html = implode("",$html);
			
			if ($html != "0") {
				$tmp = explode("{!!}",$html);
				foreach ($tmp as $line){
					$t = explode("=",$line,2);
					$search[$t[0]] = explode("{!}",$t[1]);
				}
				
				//arsort($search["dugovi"]);
				asort($search["perc"]);
				//print_rarray($search);
				
				$num=0;
				foreach ($search["perc"] as $k=>$v){
					$br_ugo = $search["ugovori"][$k];
					$plan = $search["planovi"][$k];
					$otplata = $search["otplate"][$k];
					$first_plan_date = $search["first_plan"][$k];
					$last_otplata = $search["last_otplate"][$k];
					$last_otplata_date = $search["last_otplate_date"][$k];
					$dug = $search["dugovi"][$k];
					$kom = $search["komitenti"][$k];
					
					$plan_datumi = $search["planovi_datumi"][$k];
					$otplata_datumi = $search["otplate_datumi"][$k];
					/*$tmp = explode("-",$search["planovi_datumi"][$k]);
					$plan_datumi = $tmp[2].".".$tmp[1].".".$tmp[0];
					
					$tmp = explode("-",$search["otplate_datumi"][$k]);
					$otplata_datumi = $tmp[2].".".$tmp[1].".".$tmp[0];*/
					
					$q = "SELECT rad.radnik_ime, rad.radnik_prezime, d.time, di.name as ishod, d.odgovor as odgovor_id, do.odgovor_name as odgovor, d.uplatazadana, d.kontakt_name, napomena, ishod_time, ishod_desc "
						."FROM duznici d, duznici_ishodi di, duznici_odgovori do, radnici rad, users u "
						."WHERE u.radnik_id=rad.radnik_id "
						."AND d.user=u.id "
						."AND d.ishod=di.id "
						."AND d.odgovor=do.odgovor_id "
						."AND d.ugovor='$br_ugo' "
						."ORDER BY d.time DESC";
					$history = $this->db->select2($q);
					if ($history !== false) {
						$out = "<div class=\"area\" id=\"duzniciHistoryAlert\"><h3>Istorija poziva za ugovor $br_ugo</h3><ul style=\"list-style-type:none; margin:0px; padding:0px;\">";
						foreach ($history as $row){
							
							$out .= "<li style=\"margin-bottom:5px;\">";
							
							$radnik = $row["radnik_ime"]." ".$row["radnik_prezime"];
							$vreme = date($this->getFromConfig("long_date"),$row["time"]);
							$kontakt = $row["kontakt_name"];
							$odgovor = $row["odgovor"];
							$odgovor_id = $row["odgovor_id"];
							$napomena = $row["napomena"];
							$ishod = $row["ishod"];
							$ishod_time = $row["ishod_time"]>0?date($this->getFromConfig("long_date"),$row["ishod_time"]):"";
							$ishod_desc = $row["ishod_desc"];
							
							if ($odgovor_id == 6) {
								$odgovor = str_replace("__",$row["uplatazadana"],$odgovor);
							}
							
							$out .= "<strong>$radnik, $vreme</strong>";
							$out .= "<div style=\"padding-left:10px;\">$kontakt: <i>\"$odgovor\"</i>";
							if (strlen($napomena)) {
								$out .= "<br />napomena: $napomena";
							}
							
							$out .= "<br />Ishod: $ishod";
							if (strlen($ishod_time)>0) {
								$out .= "<br />vreme: $ishod_time";
							}
							if (strlen($ishod_desc)) {
								$out .= "<br />opis: $ishod_desc";
							}
							
							$out .= "</div></li>";
						}
						$out .= "</ul></div>";
						
						$html = '<a href="javascript:void(0);" onclick="ypAjaxForm(this.nextSibling.value)">';
						$html.= '<img src="gui/icons/history.gif" border="0" />';
						$html.= '</a>';
						$html.= '<textarea style="display:none;">'.$out.'</textarea>';
						
						$h[] = $html;
					}else{
						$h[] = "&nbsp;";
					}
					
					
					$nums[]		= $num;
					$br_ugos[]	= $br_ugo;
					$koms[]		= $kom;
					$perc_otpl[]= $search["perc"][$k];
					$plans[]	= number_format($plan,2,",",".");
					$plan_dat[]	= str_replace("\n","\\n",addslashes($plan_datumi));
					$otpls[]	= number_format($otplata,2,",",".");
					$otpl_dat[]	= str_replace("\n","\\n",addslashes($otplata_datumi));
					$l_otpls[]	= number_format($last_otplata,2,",",".");
					
					if (strlen($last_otplata_date)) {
						$tmp = explode("-",$last_otplata_date,3);
						$last_otplata_date = $tmp[2].".".$tmp[1].".".$tmp[0];
						$l_otpls_d[]= " - ".$last_otplata_date;
					}else{
						if (strlen($first_plan_date)>0) {
							$tmp = explode("-",$first_plan_date,3);
							$first_plan_date = $tmp[2].".".$tmp[1].".".$tmp[0];
							$l_otpls_d[]= " - ".$first_plan_date;
						}else{
							$l_otpls_d[]= "";
						}
					}
					$dugs[]		= number_format($dug,2,",",".");
					
					$num++;
				}
				
				$this->assign("info","Ukupno: ".count($nums));
				$this->assign("num",$nums);
				$this->assign("ugovor",$br_ugos);
				$this->assign("komitent",$koms);
				$this->assign("plan",$plans);
				$this->assign("plan_datumi",$plan_dat);
				$this->assign("otplata",$otpls);
				$this->assign("otplata_perc",$perc_otpl);
				$this->assign("otplata_datumi",$otpl_dat);
				$this->assign("poslednja_otplata",$l_otpls);
				$this->assign("poslednja_otplata_datum",$l_otpls_d);
				$this->assign("dug",$dugs);
				$this->assign("history",$h);
				
			}else{
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->Nema ugovora.");
			}
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","-->Odaberite datum");
		}
		
		echo $this->parseTemplate("duznici/monthly_report.tpl");
	}
	
	function getYapFox($komid){
		$id = $this->db->getOne("SELECT yap FROM yapfox WHERE fox=$komid LIMIT 1");
		if($id !== null){
			return $id;
		}else{
			return false;
		}
	}
	
	function get_Odgovori($odgid=null){
		$ret = array();
		$res = $this->db->select2("SELECT * FROM duznici_odgovori ORDER BY odgovor_name");
		if($res !== false){
			foreach ($res as $k=>$row){
				$ret["polje_id"][$k] = $row["odgovor_id"];
				$ret["polje_name"][$k] = $row["odgovor_name"];
				if($row["odgovor_id"] == $odgid){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		
		return $ret;
	}
	
	function get_Ishodi($ishodid=null){
		$res = $this->db->select2("SELECT * FROM duznici_ishodi ORDER BY name");
		$ret = false;
		if($res !== false){
			$ret = array();
			foreach ($res as $k=>$v){
				$ret["polje_id"][$k] = $v["id"];
				$ret["polje_name"][$k] = $v["name"];
				if($v["id"] == $ishodid){
					$ret["polje_selected"][$k] = " selected";
				}else{
					$ret["polje_selected"][$k] = "";
				}
			}
		}
		return $ret;
	}
	
	function reportPozivaoci()
	{
		$f_page = (int) getFromInput("page");
		$f_page = $f_page>0?$f_page:1;
			
		$fu = intval(getFromInput("filter_ugovor"));
		$fkom = readValFromInput("filter_komitent");
		$fkon = readValFromInput("filter_kontakt");

		$fr = getFromInput("filter_radnik");

		$filter_query = "a=pozivaoci"
					  ."&filter_ugovor=$fu"
					  ."&filter_komitent=$fkom"
					  ."&filter_kontakt=$fkon"
					  ."&filter_radnik=$fr";
		$this->assign("filter_query",$filter_query);
		
		$this->assign("filter_ugovor",$fu);
		$this->assign("filter_komitent",$fkom);
		$this->assign("filter_kontakt",$fkon);
		
		$polja = $this->get_Radnici($fr,1);
			$this->assign("radnik_id",$polja["polje_id"]);
			$this->assign("radnik_ime",$polja["polje_ime"]);
			$this->assign("radnik_prezime",$polja["polje_prezime"]);
			$this->assign("radnik_selected",$polja["polje_selected"]);
			
		$setted = false;
		foreach ($_POST as $k=>$v){
			if(strlen($v)>0 && $v>=0 && !preg_match('/^a$/i',$k)){
				//echo "$k="; var_dump($v);
				$setted = true;
				break;
			}
		}
		if($setted){
			$q = "SELECT dp.*,k.komitent_id, k.komitent_name,k.komitent_predst_tel, r.radnik_ime, r.radnik_prezime "
				."FROM (((duznici_pozivaoci dp left join ugovori u on dp.ugovor_id=u.id)"
				." left join komitenti k on u.komitent=k.komitent_id)"
				." left join users on dp.user_caller=users.id)"
				." left join radnici r on  r.radnik_id=users.radnik_id ";
			$q.=" where 1=1 ";
			
			if($fu>0){
				$q .= " AND u.id=$fu ";
			}
			if(strlen($fkom)>0){
				if(preg_match('/[^\d]/',$fkom)){
					$q .= " AND k.komitent_name LIKE '%$fkom%' ";
				}else{
					$q .= " AND u.komitent=$fkom ";
				}
			}
			if(strlen($fkon)>0){
				$q .= " AND komitent_predst LIKE '%$fkon%'";
			}
			if ($fr>=0) {
				$q .= " AND r.radnik_id=$fr ";
			}
				
			$ukupno = count($this->db->select2($q));
			$num_pages = ceil($ukupno/PAGE_SIZE);
			
			// STRANE
			for ($i=0; $i<$num_pages; $i++){
				$page[$i] = $i+1;
				if ($i == ($f_page-1)) {
					$page_curr[$i] = " id=\"current\"";
				}else{
					$page_curr[$i] = "";
				}
			}
			$this->assign("page",$page);
			$this->assign("current_page",$page_curr);
			
			$q .= " ORDER BY dp.creator_time DESC";

			$q .= " LIMIT ".(($f_page-1)*PAGE_SIZE).", ".PAGE_SIZE;
						
			$res = $this->db->select2($q);
			if($res !== false){
				$ob_sum = 0;
				foreach ($res as $k=>$row){
					$index[]=$k;
					$ugovori[]		= $row["ugovor_id"];
					$komitenti[]	= $row["komitent_name"];
					$komitenti_ids[]= $row["komitent_id"];
					$datumi[]		= date($this->getFromConfig("short_date1"),$row["creator_time"]);
					$kontakti[]		= $row["komitent_predst"]."<br />".$row["komitent_predst_tel"];
					$users[]		= $row["user_caller"];
					$radnici[]		= $row["radnik_ime"]." ".$row["radnik_prezime"];
				}
				$this->assign("index",$index);
				$this->assign("datum",$datumi);
				$this->assign("ugovor",$ugovori);
				$this->assign("komitent",$komitenti);
				$this->assign("komitent_id",$komitenti_ids);
				$this->assign("kontakt",$kontakti);
				$this->assign("radnik",$radnici);
			}else{
				$this->assign("comment_start","<!--");
				$this->assign("comment_end","-->Nema pozivalaca");
			}
		}else{
			$this->assign("comment_start","<!--");
			$this->assign("comment_end","--><< Odaberite željeni kriterijum pretrage");
		}
		
		echo $this->parseTemplate("duznici/duznici_pozivaoci.tpl");
	}
	
	function zaPozivanje(){
		$userid = $this->getUserId();
		
		$day = 60*60*24;
		$display_result = "none";
		// get kampanja
		
		$q_select = "SELECT "
				."r.radnik_id, r.radnik_ime, r.radnik_prezime, "
				."k.komitent_id, k.komitent_name, k.komitent_vlasnik_name, k.komitent_direktor, k.komitent_predst, "
				."u.id, u.broj, u.iznos_bruto, u.datum, ut.name as 'ugo_tip_name',(unix_timestamp()-pr.datum_placanja) as prekoracenje_placanja";
		$q_from = "FROM ugovori u, radnici r, komitenti k, ugovori_tipovi ut,predracuni pr ";
		$q_where = "WHERE u.saradnik=r.radnik_id "
				  ." AND u.komitent=k.komitent_id "
				  ." AND u.tip_ugovora=ut.tip_id "
				  ." AND u.id=pr.ugovor_id "
				  ." AND unix_timestamp()-pr.datum_placanja>=0 ";
		$q_order = " prekoracenje_placanja desc,u.datum asc ";
		$q_group = "";
				
		$q_where .= " AND u.user_pozivalac=$userid";
			
		$q = "$q_select $q_from $q_where $q_group ORDER BY $q_order";
		$q.=" LIMIT 0,30 ";
		//echo $q; die();
		$assign = array("komid"=>array());
		$res = $this->db->select2($q);
		if ($res !== false) {
			foreach ($res as $k=>$v){
				
				$minDug = $v["iznos_bruto"]*$this->debtMinPerc/100;
				$dug = floatval($v["iznos_bruto"])-$uplaceno;
				
				//echo $v["iznos_bruto"]." - $minDug<br />";
				
				if ($dug>$minDug) {
				//if (1) {
					$key = count($assign["komid"]);
					$assign["komid"][$key] = $v["komitent_id"];
					$assign["komname"][$key] = $v["komitent_name"];
					
					$q1 = "SELECT DISTINCT telefon FROM komitenti_telefoni WHERE fax=0 AND kom_id=".$v["komitent_id"]." ORDER BY `order`"; 
					$phones = $this->db->select2($q1);
					$ph="";
					if ($phones!==false) {
						foreach ($phones as $phone){
							$ph .= "\n".$phone["telefon"];
						}
						$ph = substr($ph,1);
					}
					$assign["komphone"][$key] = $ph;
					
					$contacts = "vlasnik: ".$v["komitent_vlasnik_name"]."\n"
								."direktor: ".$v["komitent_direktor"]."\n"
								."predstavnik: ".$v["komitent_predst"];
					$assign["komcontacts"][$key] = $contacts;
					$assign["radnik_ime"][$key] = $v["radnik_ime"];
					$assign["radnik_prezime"][$key] = $v["radnik_prezime"];
					$assign["ugobroj"][$key] = $v["broj"];
					$assign["ugoiznos"][$key] = number_format($v["iznos_bruto"],2,",",".");
					$assign["ugootplata"][$key] = number_format($uplaceno,2,",",".");
					$assign["ugodug"][$key] = number_format($dug,2,",",".");
					$assign["ugodate"][$key] = datetime2str($v["datum"]);
					$assign["ugovor_tip"][$key] = $v["ugo_tip_name"];
					$assign["ugovori_ids"][$key] = $v["id"];

					$sum[$v["radnik_id"]]["vrednost"][] = $v["iznos_bruto"];
					$sum[$v["radnik_id"]]["uplaceno"][] = $uplaceno;
					$sum[$v["radnik_id"]]["duguje"][] = $dug;
					$sum[$v["radnik_id"]]["rad_ime"] = $v["radnik_ime"];
					$sum[$v["radnik_id"]]["rad_prezime"] = $v["radnik_prezime"];
					
					list($planid,$brrata,$avans,$avans_date) = $this->db->getRow("SELECT plan_id, broj_rata, avans_bruto, avans_date FROM ugovori_plan_otplate WHERE ugovor_id=".$v["id"]." LIMIT 1");
					
					$q1 = "SELECT bruto, datum "
						."FROM ugovori_plan_rate "
						."WHERE rata_plan=$planid "
						."ORDER BY datum";
					$plans = $this->db->select2($q1);
					$pl = "<table><tr><td>AVANS:</td><td title=\"".datetime2str($avans_date)."\">".number_format($avans,2,",",".")."</td></tr>";
					$pl_last = "";
					if ($plans!==false && count($plans)>0) {
						if ($avans>0 && $brrata<count($plans)) {
							array_splice($plans,0,1);
						}
						foreach ($plans as $plan){
							$pl .= "<tr><td>".int2date($plan["datum"])."</td><td>".number_format($plan["bruto"],2,",",".")."</td></tr>";
						}
						$pl_last = int2date($plans[count($plans)-1]["datum"]);
					}else{
						$ad = datetime2str($avans_date);
						$pl_last = date2int($ad)>0?$ad:"";
					}
					$assign["ugoplan"][$key] = "$pl</table>";
					$assign["ugoplan_last"][$key] = $pl_last;
				}
			}
						
			//
			//
			//echo "<pre>";var_dump($assign["ugoplan_last"]);echo "</pre>";
			//print_rarray($assign);
			foreach ($assign as $k=>$v){
				$this->assign($k,$v);
			}
		}
		
		return $this->parseTemplate("duznici/duznici_za_pozivanje.tpl");
	}
}

?>